import React, { PureComponent } from "react";
import {
    Text,
    View,
    Image,
    TextInput,
    Alert,
    Platform,
    TouchableOpacity,
    Keyboard,
    StyleSheet, ScrollView, FlatList, TouchableWithoutFeedback
} from "react-native";
import {
    statusBarHeight,
    safeAreaBottomHeight,
    LoginToken,
    screenHeight,
    UserInfo, screenWidth,HistoryPhone
} from "../../../util/AdapterUtil";
import NavigationService from "../../../components/NavigationService";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import actions from "../../../models/actions";
import { connect } from "react-redux";
import NavigationBar from "../../../components/navigationBar";
import MD5 from "react-native-md5";
import image from "../../../assets/image";
import * as requestApi from "../../../util/requestApi";
import _ from "lodash";

class LoginScreen extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      phoneText: "",
      password: "",
      token: "",
      isselected: true,
      isVisible: false, //是否显示密码
      showPhones: false, //是否显示输入记录
      phoneData: [], //是否显示输入记录
    };
  }

  componentDidMount() {
      global.storage.load({
          key: HistoryPhone,
      }).then(ret => {
          if (ret != null && Array.isArray(ret)) {
              this.setState({
                  phoneData :ret
              });
          }
      }).catch(err => {
      });
      //登录过期 进入登录页面就清除用户数据
      this.props.getUserInfo({clear: true}); //清楚用户数据
  }

  render() {
    return (
        <TouchableWithoutFeedback
            onPress={() => {
                this.setState({
                    showPhones: false
                });
            }}
        >
          <View style={{ flex: 1, backgroundColor: "#fff" }}>
            <NavigationBar
              navigation={this.props.navigation}
              isBack={true}
              isDrawer={() => {
                NavigationService.reset("Drawer");
              }}
            />
            <KeyboardAwareScrollView>
              <TouchableOpacity
                onPress={this.hiddenKeyborad.bind(this)}
                activeOpacity={1}
                style={{
                  height:
                    screenHeight - safeAreaBottomHeight - statusBarHeight - 44 - 10
                }}
              >
                <Text
                  style={{
                    color: "#202020",
                    marginTop: 30,
                    fontSize: 35,
                    fontWeight: "bold",
                    height: 40,
                    marginLeft: 15
                  }}
                >
                  登录
                </Text>
                <View
                  style={{
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    height: 60,
                    marginTop: 30,
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center",
                    justifyContent: "center"
                  }}
                >
                  <TextInput
                    style={{
                      padding: 0,
                      color: "#202020",
                      fontSize: 16,
                      flex: 1,
                      height: 40
                    }}
                    placeholder={"请输入手机号"}
                    keyboardType={"numeric"}
                    maxLength={11}
                    onFocus = {()=>{
                        this.setState({
                            showPhones :true
                        });
                    }}

                    value={this.state.phoneText}
                    onChangeText={text => {
                      const newText = text.replace(/[^\d]+/, "");
                      let show = true;
                      if (newText.length >= 11) {
                          show = false;
                      }
                      this.setState({
                        showPhones:show,
                        phoneText: newText
                      });
                    }}
                  />
                </View>

              {/*展示输入记录*/}
              {this.state.showPhones &&
              this.state.phoneData &&
              this.state.phoneData.length > 0
                  ? this.showHistoryPhoneView()
                  : null}

                <View
                  style={{
                    marginLeft: 15,
                    height: 1,
                    backgroundColor: "#ccc",
                    transform: [{ scaleY: 0.5 }]
                  }}
                />

                <View
                  style={{
                    backgroundColor: "#fff",
                    flexDirection: "row",
                    height: 60,
                    paddingLeft: 20,
                    paddingRight: 15,
                    alignItems: "center",
                    justifyContent: "center"
                  }}
                >
                  <TextInput
                    style={{
                      padding: 0,
                      color: "#202020",
                      fontSize: 16,
                      flex: 1,
                      height: 40
                    }}
                    placeholder={"请输入密码"}
                    secureTextEntry={!this.state.isVisible}
                    selectionColor={"#4A90E2"}
                    maxLength={16}
                    value={this.state.password}
                    onChangeText={text => {
                      if (this.isPassword(text)) {
                        Toast.show("密码只能输入字母和数字", 1000);
                      }
                      let newtext = text.replace(/[^\da-zA-Z]+/, "");
                      if (text != null && text.length >= 16) {
                        Toast.show("密码最多16个字符", 1000);
                      } else {
                        this.setState({
                          password: newtext
                        });
                      }
                    }}
                  />
                  <TouchableOpacity
                    onPress={() => {
                      this.setState({
                        isVisible: !this.state.isVisible
                      });
                    }}
                  >
                    <Image
                      style={{ marginLeft: 20, padding: 0, width: 20, height: 20 }}
                      source={
                        this.state.isVisible ? image.ic_visible : image.ic_invisible
                      }
                    />
                  </TouchableOpacity>
                </View>

                <View
                  style={{
                    marginLeft: 15,
                    height: 1,
                    backgroundColor: "#ccc",
                    transform: [{ scaleY: 0.5 }]
                  }}
                />

                <View
                  style={{
                    flexDirection: "row",
                    marginTop: 10,
                    height: 30,
                    alignItems: "center"
                  }}
                >
                  <TouchableOpacity
                    style={{
                      width: 50,
                      height: 40,
                      justifyContent: "center",
                      alignItems: "center",
                      marginLeft: 5
                    }}
                    onPress={() => {
                      this.setState({
                        isselected: !this.state.isselected
                      });
                    }}
                  >
                    <View
                      style={{
                        height: 12,
                        width: 12,
                        justifyContent: "center",
                        alignItems: "center",
                        borderRadius: 2,
                        borderWidth: 1,
                        borderColor: "#222"
                      }}
                    >
                      <Image
                        style={{ height: 10, width: 10 }}
                        source={this.state.isselected ? image.ic_selected : null}
                        resizeMode={"cover"}
                      />
                    </View>
                  </TouchableOpacity>

                  <Text style={{ marginLeft: 0, color: "#222", fontSize: 14 }}>
                    同意
                  </Text>
                  <TouchableOpacity
                    style={{
                      marginLeft: 10,
                      justifyContent: "center",
                      alignItems: "center"
                    }}
                    onPress={this.openAgreement.bind(this)}
                  >
                    <Text style={{ color: "#4A90E2", fontSize: 14 }}>
                      《用户服务协议》
                    </Text>
                  </TouchableOpacity>
                </View>
                <TouchableOpacity
                  style={{
                    marginTop: 10,
                    marginLeft: 20,
                    marginRight: 20,
                    height: 45,
                    borderRadius: 3,
                    backgroundColor: "#4A90E2",
                    justifyContent: "center",
                    alignItems: "center"
                  }}
                  onPress={this.loginAction.bind(this)}
                >
                  <Text style={{ color: "#fff", fontSize: 14 }}>登陆</Text>
                </TouchableOpacity>

                <View
                  style={{
                    flexDirection: "row",
                    marginTop: 10,
                    height: 30,
                    justifyContent: "center",
                    alignItems: "center"
                  }}
                >
                  <TouchableOpacity
                    style={{
                      marginLeft: 10,
                      justifyContent: "center",
                      alignItems: "center"
                    }}
                    onPress={this.openForgetPassword.bind(this)}
                  >
                    <Text style={{ color: "#4A90E2", fontSize: 14 }}>
                      忘记密码？
                    </Text>
                  </TouchableOpacity>
                </View>
              </TouchableOpacity>
            </KeyboardAwareScrollView>
            <View style={{ height: safeAreaBottomHeight }} />
          </View>
        </TouchableWithoutFeedback>
    );
  }

  hiddenKeyborad() {
      this.setState({
          showPhones: false
      });
      Keyboard.dismiss();
  }

  showHistoryPhoneView() {
   return(
       <View
           style={{
               zIndex: 99,
               position: "absolute",
               top: 30 + 40 + 30 + 60 + 5,
               right: 0,
               width: screenWidth,
               height: 500,
               backgroundColor: "#00000000"
           }}>

           <View
               style={{
                   marginTop: 0,
                   marginLeft: 14,
                   borderRadius: 5,
                   borderWidth: 1,
                   borderColor: "#ccc",
                   width: screenWidth - 28,
                   maxHeight: 360,
                   backgroundColor: "#fff"
               }}>
               <ScrollView>
                   <FlatList
                       style={{ backgroundColor: "#fff" }}
                       scrollEnabled={false}
                       data={this.state.phoneData}
                       horizontal={false}
                       keyExtractor={(item, index) => index.toString()}
                       renderItem={this._renderItem}
                   />
               </ScrollView>
           </View>
           <TouchableWithoutFeedback
               onPress={() => {
                   this.setState({
                       showPhones: false
                   });
               }}>
               <View  style={{
                   flex:1
               }}/>
           </TouchableWithoutFeedback>
       </View>
        )
  }

    _renderItem = ({ item }) => (
        <MyListItem onPressItem={this._onPressItem.bind(this)} item={item} />
    );

    _onPressItem = item => {
        this.setState({
            phoneText: item + "",
            showPhones :false
        });
    };

  openAgreement() {
    //跳转服务协议
    NavigationService.navigate("ServiceAgreementScreen");
  }

  openForgetPassword() {
    //跳转服务协议
    NavigationService.navigate("ForgetPassword");
  }

  loginAction() {
    let { phoneText, password, isselected } = this.state;
    if (
      typeof phoneText == "undefined" ||
      phoneText == null ||
      phoneText == ""
    ) {
      Toast.show("请输入手机号", 1000);
      return;
    }
    if (this.isPhoneNumber(phoneText)) {
      if (
        typeof password == "undefined" ||
        password == null ||
        password == ""
      ) {
        Toast.show("请输入密码", 1000);
        return;
      }
      if (password.length < 8) {
        Toast.show("密码不能小于8位", 1000);
        return;
      }
      if (!isselected) {
        Toast.show("你还没阅读服务协议", 1000);
        return;
      }
      let sign = MD5.hex_md5(password);
      Loading.show();
      this.props
        .getLoginToken({
          username: phoneText,
          password: sign,
          terminal: "receiptapp"
        })
        .then(res => {
          Loading.hide();
          if (
            res &&
            res.httpCode == 200 &&
            res.data &&
            typeof res.data.hsAuthorization != "undefined" &&
            res.data.hsAuthorization != null &&
            res.data.hsAuthorization !== ""
          ) {
            global.token = res.data.hsAuthorization; //全局存储token
            this.saveDataToStorage(res.data); //token存入文件中
            this._havePayPassword(); //查看是否有支付密码
            Toast.show("登录成功", 1000);
            //跳转首页
            NavigationService.reset("Drawer");
            this.props.getUserInfo(); //获取用户信息存入strore
          } else {
            Toast.show(res.message, 1000);
          }
        })
        .catch(err => {
          Loading.hide();
          Toast.show("网络问题，请重试", 1000);
        });
    } else {
      Toast.show("手机号格式不对", 1000);
    }
  }

  isPhoneNumber = phoneNumber => {
    const reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    return reg.test(phoneNumber);
  };

  isPassword = password => {
    const reg = /[^\da-zA-Z]+/;
    return reg.test(password);
  };

  //保存数据
  saveDataToStorage = async data => {
    //保存token
    global.storage.save({
      key: LoginToken,
      data: data.hsAuthorization,
      expires: null
    });
    //保存用户信息
    global.storage.save({
      key: UserInfo,
      data: data,
      expires: null
    });
    if (!_.includes(this.state.phoneData,data.phone)) {
        this.state.phoneData.push(data.phone)
    }
     //保存用户信息
    global.storage.save({
      key: HistoryPhone,
      data: this.state.phoneData,
      expires: null
    });
  };

  //获取当前用户是否有支付密码
  _havePayPassword = () => {
    requestApi
      .havePayPassword()
      .then(res => {
        //保存用户是否有支付密码
        if (res == 1) {
          global.havaPayPassword = true;
        } else {
          global.havaPayPassword = false;
        }
        //保存用户信息
        global.storage.save({
          key: "havaPayPassword",
          data: res == 1 ? true : false,
          expires: null
        });
      })
      .catch(err => {
        global.havaPayPassword = true; //请求失败默认有支付密码
      });
  };
}

class MyListItem extends PureComponent {
    _onPress = () => {
        this.props.onPressItem(this.props.item);
    };

    render() {
        return (
            <View style={{ height: 40, width: "100%" }}>
                <TouchableOpacity
                    style={{
                        flexDirection: "row",
                        height: 30,
                        marginLeft: 15,
                        marginTop: 5,
                        marginRight: 15,
                        marginBottom: 5,
                        alignItems: "center",
                        justifyContent: "flex-start"
                    }}
                    onPress={this._onPress.bind(this)}
                >
                    <Text style={{ color: "#222", fontSize: 18 }}>
                        {this.props.item}
                    </Text>
                </TouchableOpacity>
                <View
                    style={{
                        marginLeft: 5,
                        height: 1,
                        backgroundColor: "#DDDDDD",
                        transform: [{ scaleY: 0.5 }]
                    }}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
  loginTitle: {
    marginLeft: 15,
    marginTop: 25,
    color: "#202020",
    fontSize: 30,
    fontWeight: "bold"
  }
});

export default connect(
  ({ userInfo }) => ({
    userInfo
  }),
  {
    getLoginToken: actions.getLoginToken,
    getUserInfo: actions.getUserInfo
  }
)(LoginScreen);
